<?php
namespace app\appadmin\controller\v1;
use app\app\Appbase;

class Coupons extends Appbase 
{
	
//	/**
//  * 构造函数自动执行
//  * @return null
//  */
//  public function __construct(){
//  	if( request()->identity == 1 ){
//    		return $this->ReError( '管理员不能进行当前操作！' );
//  	}
//		parent::__construct();
//  }
	
	/**
	* 首页
	* /appAdmin/v1/coupons/index
	* 需要登录 
	* @is_need_login true
	* @param $type 1今日，2本月，3本年
	*/
	public function index($type=1){
		$identity = request()->identity;
		$wxUid = request()->wxUid;
		try {
			$t = $type == 2 ? 'month' : ($type == 3 ? 'year' : 'today');
			//TODO 营业额
			$data['prices'] = model('CouponUser')->alias('a')
				->leftJoin("order b",'a.id = b.coupon_id')
				->where('a.oid_uid',$wxUid)
				->whereTime('a.use_time',$t)
				->sum('b.pay_price');
				
			//TODO 给多少人发送
			$data['user_num'] = model('CouponUser')
				->where('oid_uid',$wxUid)
				->whereTime('add_time',$t)
				->count();
			//TODO 获得客户数量
			$data['get_user_num'] = model('CouponUser')
				->where('oid_uid',$wxUid)
				->where('status',1)
				->whereTime('use_time',$t)
				->count();
			//返回
			return $this->ReSucess($data);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 选择优惠券
	* /appAdmin/v1/index/select
	* 需要登录 
	* @is_need_login true
	*/
	public function select(){
		$identity = request()->identity;
		$wxUid = request()->wxUid;
		try {
			$data = model('CouponUser')
				->where('uid',$wxUid)
				->where('is_give',1)
				->where('num > use_num')
				->where(function ($query) {
					$d =  date("Y-m-d"); $h =  date("H:i:s"); $dh =  date("Y-m-d H:i:s");
					$query->where(function ($query) use($d,$h,$dh) {
						$query->where('can_day','=',0);
					});
					$query->whereor(function ($query) use($d,$h,$dh) {
						$query = $query->where('can_day','>',0);
						$query = $query->where('start_time','<=',$d);
						$query = $query->where([['','exp',\Db::raw("date_format(now(),'%Y-%m-%d')<= stop_time")]]);
					});
				})
				->page(input('pageIndex') ?: 1,input('pageSize') ?: 20)
				->order('id','desc')
				->select();
			return $this->ReSucess($data);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 获取优惠券明细
	* /appAdmin/v1/coupons/details
	* 需要登录 
	* @is_need_login true
	*/
	public function details($id=''){
		try {
			$result = model('CouponUser')->details($id);
			return $this->ReSucess($result);	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
}



